package easycloud.ecs.agent.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import easycloud.ecs.common.exception.ConfigException;

public final class AgentConfigUtils {

	private static final Log logger = LogFactory.getLog(AgentConfigUtils.class);

	/**
	 * 
	 * @return
	 * @throws ConfigException
	 */
	public static AgentConfig getAgentConfig(File configFile)
			throws ConfigException {
		AgentConfig config = new AgentConfig();
		Properties prop = new Properties();
		try {
			FileInputStream fis = new FileInputStream(configFile);
			prop.load(fis);
			config.setEmail(prop.getProperty("email"));
			config.setPassword(prop.getProperty("password"));
			config.setProviderid(Integer.parseInt(prop
					.getProperty("providerid")));
			config.setConfigFile(configFile);
			fis.close();
		} catch (FileNotFoundException e) {
			AgentConfigUtils.logger.warn("Config file not found", e);
			throw new ConfigException("Config file not found: " + configFile);
		} catch (IOException e) {
			AgentConfigUtils.logger.warn("IO Exception", e);
			throw new ConfigException("IO Exception");
		}
		return config;
	}

	/**
	 * 
	 * @param config
	 * @throws ConfigException
	 */
	public static void saveAgentConifg(AgentConfig config)
			throws ConfigException {
		Properties prop = new Properties();
		try {
			prop.setProperty("email", config.getEmail());
			prop.setProperty("password", config.getPassword());
			prop.setProperty("providerid",
					String.valueOf(config.getProviderid()));
			FileOutputStream fos = new FileOutputStream(config.getConfigFile());
			prop.store(fos, "");
			fos.close();
		} catch (FileNotFoundException e) {
			AgentConfigUtils.logger.warn("Config file not found", e);
			throw new ConfigException("Config file not found");
		} catch (IOException e) {
			AgentConfigUtils.logger.warn("IO Exception", e);
			throw new ConfigException("IO Exception");
		}
	}

	private AgentConfigUtils() {

	}

}
